<template>
  <div>
    <div v-loading="loading">
      <upload-seal
        accept="image/*"
        :action="`/cfca/seal?userId=${cfcaUserId}`"
        ref="upload"
        listType="picture-card"
        @success="handleSuccess"
        multiple
        :cfcaUserId="cfcaUserId"
        :before-upload="beforeAvatarUpload"
        :file-list="fileList"
      ></upload-seal>
      <div class="py-2">
        <el-button @click="upload" class="btn-long">新增公章</el-button>
      </div>
      <div class="card p-3">
        <div>公章列表</div>
        <div class="image-warp">
          <div v-for="(p, index) of tableData" class="image-item" :key="index">
            <upload-seal
              accept="image/*"
              auto-upload
              :action="`/cfca/seal?userId=${cfcaUserId}&sealId=${p.sealId}`"
              :cfcaUserId="cfcaUserId"
              :isPut="true"
              @success="getData"
              :showFileList="false"
              singleImage
              :before-upload="beforeAvatarUpload"
              :file-list="setList(p.imageData)"
            ></upload-seal>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getData } from '@/common/api/cfca'
import UploadSeal from '@/credit/views/cadmin/seal/UploadSeal'
export default {
  components: {
    UploadSeal,
  },
  props: {
    visible: Boolean,
  },
  data() {
    return {
      tableData: [],
      fileList: [],
      previewIndex: 0,
      previewVisible: false,
      previewImages: [],
      loading: false,
    }
  },

  computed: {
    ...mapGetters(['cfcaUserId']),
  },

  created() {
    this.getData()
  },
  methods: {
    setList(url) {
      return [{ url }]
    },
    handleClose() {
      this.fileList = []
      this.$emit('update:visible', false)
    },
    preview(index) {
      this.previewIndex = index
      this.previewVisible = true
    },
    handleSuccess() {
      this.fileList = []
      this.getData()
    },
    async getData() {
      await this.$store.dispatch('getCfca', true)
      if (!this.cfcaUserId) {
        return
      }
      this.loading = true
      getData('seal', { userId: this.cfcaUserId })
        .then(res => {
          const data = (res && res.data) || {}
          this.tableData = data.sealQuery.seals || []
          this.tableData.map(item => {
            item.imageData = 'data:image/png;base64,' + item.imageData
            return item
          })
          this.previewImages = this.tableData.map(img => ({
            src: img.imageData,
          }))
        })
        .finally(() => {
          this.loading = false
        })
    },
    downLoad(imgbase) {
      const aLink = document.createElement('a')
      aLink.download = '公章.png'
      const blob = this.base64ToBlob(imgbase)
      aLink.href = URL.createObjectURL(blob)
      aLink.click()
    },
    base64ToBlob(content) {
      let parts = content.split(';base64,')
      let contentType = parts[0].split(':')[1]
      let raw = window.atob(parts[1])
      let rawLength = raw.length

      let uInt8Array = new Uint8Array(rawLength)

      for (let i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i)
      }
      return new Blob([uInt8Array], { type: contentType })
    },
    upload() {
      this.$refs.upload.submit()
    },
    beforeAvatarUpload(file) {
      const fileType = ['image/jpeg', 'image/png']
      const isJPG = fileType.includes(file.type)
      const isLt2M = file.size / 1024 < 100
      return new Promise((resolve, reject) => {
        if (!isJPG) {
          this.$message.error('上传图片只能是 JPG/PNG 格式!')
          return reject(new Error(false))
        }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 100KB!')
          return reject(new Error(false))
        }
        return resolve(isJPG && isLt2M)
      })
    },
  },
}
</script>
<style lang="scss" scoped>
.image-warp {
  display: flex;
  flex-wrap: wrap;
  .image-item {
    margin: 10px 20px 0px 0px;
  }
}
</style>
